<?php
class Encryption {
    private $key;
    private $cipher = "AES-256-CBC";
    private $iv_length;

    public function __construct() {
        // 从环境变量或配置文件中获取密钥
        $this->key = getenv('ENCRYPTION_KEY') ?: 'your-secret-key-here';
        $this->iv_length = openssl_cipher_iv_length($this->cipher);
    }

    public function encrypt($data) {
        // 如果数据是数组，先转换为JSON
        if (is_array($data)) {
            $data = json_encode($data);
        }

        // 生成随机IV
        $iv = openssl_random_pseudo_bytes($this->iv_length);

        // 加密数据
        $encrypted = openssl_encrypt(
            $data,
            $this->cipher,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv
        );

        // 将IV和加密数据组合在一起
        $combined = $iv . $encrypted;

        // 返回base64编码的结果
        return base64_encode($combined);
    }

    public function decrypt($encryptedData) {
        try {
            // 解码base64数据
            $decoded = base64_decode($encryptedData);
            
            // 提取IV和加密数据
            $iv = substr($decoded, 0, $this->iv_length);
            $encrypted = substr($decoded, $this->iv_length);

            // 解密数据
            $decrypted = openssl_decrypt(
                $encrypted,
                $this->cipher,
                $this->key,
                OPENSSL_RAW_DATA,
                $iv
            );

            if ($decrypted === false) {
                throw new Exception('Decryption failed');
            }

            // 尝试解析JSON
            $result = json_decode($decrypted, true);
            
            // 如果解析成功，返回数组，否则返回原始字符串
            return json_last_error() === JSON_ERROR_NONE ? $result : $decrypted;
        } catch (Exception $e) {
            error_log('Decryption error: ' . $e->getMessage());
            return null;
        }
    }
} 